<template>
	<view class="nice-nav-2">
		<u-navbar title="签到积分" titleColor="#fff" backIconColor="#fff"></u-navbar>
		<view class="pad-base">
			<view class="h-box mg-b-sm top-bar">
				<picker class="flex-extend" :range="storeOption || []" range-key="name" @change="handleStoreChange">
					<view class="h-box justify-center">
						<text class="mg-r-xs">{{storeOption[selectedStoreIdx].name}}</text>
						<u-icon name="arrow-down"></u-icon>
					</view>
				</picker>
				<!-- <u-search v-model="keywords" @search="reload" @custom="reload" @clear="reload"></u-search> -->
			</view>
			<view class="integral-card">
				<view class="h-box">
					<text class="text-integral-label flex-extend">总积分￥</text>
					<view class="h-box link">
						<text @click="navToRule">使用规则&gt;</text>
						<u-line direction="col" length="26rpx" color="#fff" margin="0 20rpx"></u-line>
						<text @click="navToHistory">查询明细&gt;</text>
					</view>
				</view>
				<text class="text-integral">{{total || 0}}</text>
			</view>
			<u-sticky>
				<u-tabs :list="tabs" active-color="#fff" :active-item-style="activeItemStyle" :current="tabIdx"
					:is-scroll="false" :show-bar="false" @change="handleTabChange"></u-tabs>
			</u-sticky>
			<view class="mg-t-base">
				<view v-show="tabIdx == 0">
					<uni-list v-if="tabs[0].list.length">
						<uni-list-item v-for="(item, index) in tabs[0].list" :key="index" :showArrow="false"
							:clickable="false">
							<view class="h-box">
								<u-image border-radius="12rpx" :src="item.scriptInfo[0].cover" width="142rpx"
									height="182rpx"></u-image>
								<view class="flex-v mg-l-sm flex-extend">
									<text class="flex-extend text-bold text-title">
										{{item.scriptInfo[0].name}}
									</text>
									<text>角色：{{item.signDetail.role || ''}}</text>

									<text>DM：{{item.dmInfo[0].nickname || item.dmInfo[0].username || ''}}</text>
									<view class="h-box">
										<text>门店：</text>
										<marquee-scroll width="200rpx">
											<text>{{item.storeInfo[0].name}}</text>
										</marquee-scroll>
									</view>
									<view class="h-box">
										<text>签到时间 </text>
										<marquee-scroll width="200rpx">
											<uni-dateformat :threshold="[0, 0]" :date="item.signDetail.signTime">
											</uni-dateformat>
										</marquee-scroll>
									</view>
								</view>
								<view>
									<view class="h-box">
										<u-image
											src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_coin@2x.png"
											width="28rpx" height="28rpx"></u-image>
										<text class="text-rewards">+{{item.signDetail.rewards}}</text>
									</view>
									<view
										style="width: 120rpx;height: 40rpx;;background: linear-gradient(180deg, #FF9F43 0%, #FD5C47 100%);border-radius: 28rpx;display: flex;align-items: center;justify-content: center;"
										@click="evaluate(item)" v-if="!item.signDetail.isEvaluate">
										<u-icon name="edit-pen" color="#FFFFFF" size="28"></u-icon>
										<view style="color: #FFFFFF;font-size: 20rpx;margin: 3rpx;margin-left: 8rpx;"
											class="text-rewards">待评价</view>
									</view>
									<view v-else
										style="width: 100rpx;height: 40rpx;background: linear-gradient(180deg, #FF9F43 0%, #FD5C47 100%);border-radius: 28rpx;display: flex;align-items: center;justify-content: center;">
										<view style="color: #FFFFFF;font-size: 20rpx;margin: 3rpx;margin-left: 8rpx;"
											class="text-rewards">已评价</view>
									</view>
								</view>

							</view>
						</uni-list-item>
					</uni-list>
					<uni-load-more :status="tabs[0].loadingStatus"></uni-load-more>
				</view>
				<unicloud-db v-show="tabIdx == 1" ref="udb2"
					v-slot:default="{data, pagination, loading, hasMore, error}" :collection="collectionList2"
					field="uid,taskId{title,detail,rewards,rewards2},checkRecords,createTime,deadline,awardDetail"
					:where="where2" orderby="createTime desc">
					<view v-if="error">{{error.message}}</view>

					<view v-else-if="data">
						<view class="task-item" :class="{'expired': isExpired(item)}" v-for="(item, index) in data"
							:key="index" @click="handleTaskItemClick(item)">
							<view class="flex-v">
								<view class="h-box">
									<u-image :src="getTaskIcon(item)" width="82rpx" height="82rpx"></u-image>
									<view class="flex-v mg-l-sm flex-extend u-line-1">
										<view class="h-box">
											<view class="flex-extend" style="width: 1px;">
												<marquee-scroll width="100%">
													<text class="text-title">
														{{item.taskId.length ? item.taskId[0].title : '-'}}
													</text>
												</marquee-scroll>
											</view>
											<view v-if="item.taskId[0] && item.taskId[0].rewards" class="h-box mg-l-sm">
												<u-image
													src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_coin@2x.png"
													width="28rpx" height="28rpx"></u-image>
												<text class="text-rewards">+{{item.taskId[0].rewards}}</text>
											</view>
											<view v-if="item.taskId[0] && item.taskId[0].rewards2"
												class="h-box mg-l-sm">
												<u-image
													src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_packet.png"
													width="26rpx" height="32rpx"></u-image>
												<text class="text-rewards">+{{item.taskId[0].rewards2 / 100}}</text>
											</view>
										</view>


										<!-- <view class="u-line-1">{{item.taskId[0].detail}}</view> -->
									</view>
									<view style="padding-right: 20rpx;" v-if="item.awardDetail"
										@click.stop="onDetail(item.awardDetail)">
										<view style="background-color: #FF9F43;border-radius: 50rpx;">
											<view style="font-size: 24rpx;margin: 20rpx;color: white;">领奖励</view>
										</view>
									</view>
								</view>
								<view class="h-box item-bottom">
									<view class="flex-extend">
										<text>截止时间：</text>
										<uni-dateformat v-if="item.deadline" :threshold="[0, 0]" :date="item.deadline">
										</uni-dateformat>
										<text v-else>无限制</text>
									</view>
									<text class="status-tag" :class="[statusClass(item)]">{{parseStatus(item)}}</text>
								</view>
							</view>
						</view>
					</view>
					<uni-load-more :status="loading?'loading':(hasMore ? 'more' : 'noMore')"></uni-load-more>
				</unicloud-db>
			</view>
		</view>
		<u-popup v-model="onDetailIsShow" mode="center" close-icon-size="20" border-radius="14" length="80%" closeable>
			<view style="margin: 20rpx;"><u-button @click="onDetailClick(taskDetail)" type="success" size="mini">复制</u-button>
			</view>
			<view class="mg-base" style="margin-top: 50rpx;">
				<u-parse :html="taskDetail"></u-parse>
			</view>
		</u-popup>

		<u-popup v-model="evaluationIsShow" mode="bottom" border-radius="14" @close="evaluateClear">
			<view class="pad-base">
				<view style="display: flex;justify-content: space-between;">
					<view><u-button size="mini" shape="circle" @click="evaluateClear">取消</u-button></view>
					<view style="font-size: 32rpx;">写评价</view>
					<view><u-button type="warning" size="mini" shape="circle" @click="onEvaluate">发布</u-button></view>
				</view>
				<view style="display: flex;margin-top: 10px;">
					<view style="font-size: 30rpx;color: #666666;">环境评分</view>
					<view>

						<u-rate size="35" active-color="#FF9F43" :allowHalf="true" :count="5"
							v-model="evaluationObj.environment"></u-rate> {{evaluationObj.environment}}分
						<!-- <uni-rate size="18" value="5"></uni-rate> -->



					</view>
				</view>
				<view style="display: flex;">
					<view style="font-size: 30rpx;color: #666666;">服务评分</view>
					<view>
						<u-rate size="35" active-color="#FF9F43" :allowHalf="true" :count="5"
							v-model="evaluationObj.serve"></u-rate> {{evaluationObj.serve}}分
					</view>
				</view>
				<view style="display: flex;">
					<view style="font-size: 30rpx;color: #666666;">剧本评分</view>
					<view>
						<u-rate size="35" active-color="#FF9F43" :allowHalf="true" :count="5"
							v-model="evaluationObj.script"></u-rate>{{evaluationObj.script}}分
					</view>
				</view>
				<view style="display: flex;">
					<view style="font-size: 30rpx;color: #666666;">D M评分 </view>
					<view>
						<u-rate size="35" active-color="#FF9F43" :allowHalf="true" :count="5"
							v-model="evaluationObj.clientdm"></u-rate>{{evaluationObj.clientdm}}分
					</view>
				</view>
				<u-line margin="20rpx 0" color="#A4A4A4"></u-line>
				<view>
					<view style="font-size: 30rpx;">
						意见反馈
					</view>
					<view style="">
						<uni-easyinput type="textarea" placeholder="请如实填写您的真实感受,以便我们改进为您提供更好的服务~"
							placeholder-style="font-size:30rpx" v-model="evaluationObj.clientfeedback" />
					</view>
				</view>


			</view>
		</u-popup>


	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	const db = uniCloud.database()
	const statusDic = {
		'0': '待完成',
		'1': '待审核',
		'2': '已完成',
		'3': '待进一步提交',
		'-1': '未通过'
	}
	const storeSigner = uniCloud.importObject('storeSigner')
	export default {
		data() {
			return {
				total: 0,
				collectionList1: "t3ds-store-sign,t3ds-script,t3ds-store",
				collectionList2: "t3ds-marketing-task-user,t3ds-marketing-task",
				// loadMore: {
				// 	contentdown: '',
				// 	contentrefresh: '',
				// 	contentnomore: ''
				// },
				tabIdx: 0,
				tabs: [{
					name: '剧本签到记录',
					list: [],
					pageNum: 0,
					pageSize: 20,
					total: 0,
					loadingStatus: 'more'
				}, {
					name: '我的任务'
				}],
				activeItemStyle: {
					backgroundColor: '#FF7D66',
					border: '2px solid #fff',
					borderRadius: '40rpx'
				},
				activeItemStyleaward: {
					backgroundColor: 'rgb(254,255,154)',
					border: '2px solid #fff',
					borderRadius: '40rpx'
				},
				storeList: null,
				selectedStoreIdx: 0,
				evaluationIsShow: false,
				evaluationObj: {
					environment: 0,
					serve: 0,
					script: 0,
					clientdm: 0,
					clientfeedback: '',
					signId: ''
				},
				onDetailIsShow: false,
				taskDetail: ''
			}
		},
		onLoad() {
			this.reload()
		},
		onShow() {
			if (this.needReload) {
				this.needReload = false
				this.reload()
			}
		},
		computed: {
			...mapState(['userInfo']),
			where2() {
				let p = [`uid=='${this.userInfo._id}'`]
				if (this.selectedStoreIdx != 0) {
					p.push(`storeId == '${this.storeOption[this.selectedStoreIdx]._id}'`)
				}
				return p.join('&&')
			},
			storeOption() {
				return [{
					name: '全部门店'
				}].concat(this.storeList || [])
			}
		},
		onPullDownRefresh() {
			if (this.tabIdx == 1) {
				this.$refs.udb2.loadData({
					clear: true
				}, () => {
					uni.stopPullDownRefresh()
				})
			} else {
				this.reload()
			}
		},
		
		onReachBottom() {
			if (this.tabIdx == 1) {
				this.$refs.udb2.loadMore()
			} else {
				this.loadMore()
			}
		},
		methods: {
			...mapMutations(['updateUserInfo']),
			navToHistory() {
				uni.navigateTo({
					url: '/pagesMarketing/integral-history'
				})
			},
			navToRule() {
				uni.navigateTo({
					url: '/pagesMarketing/integral-rule'
				})
			},
			async loadStoreList() {
				if (this.storeList) {
					return
				}
				this.storeList = await this.$dbHelper.getList('t3ds-store', {
					where: 'type == "t3ds"',
					field: '_id,name'
				})
			},
			handleStoreChange(e) {
				this.selectedStoreIdx = e.detail.value
				this.$nextTick(() => {
					this.reload()
				})
			},
			
			onDetailClick(value) {
				uni.setClipboardData({
					data: value,
					success: () => {
						// uni.showModal({
						// 	title: "提示",
						// 	content: "客服微信已复制，请去微信添加",
						// 	confirmText: "知道了",
						// 	showCancel: false
						// })
					}
				})
			},
			
			async reload() {
				await this.loadStoreList()
				let tab = this.tabs[this.tabIdx]
				// let userInfo = await this.$dbHelper.getById('uni-id-users', this.userInfo._id, {
				// 	field: 'integral'
				// })
				this.total = await storeSigner.getMyIntegral(this.selectedStoreIdx != 0 ? this.storeOption[this
					.selectedStoreIdx]._id : '')
				// this.updateUserInfo(Object.assign(this.userInfo, userInfo))
				if (this.tabIdx == 0) {
					if (tab.loadingStatus == 'loading') {
						return
					}
					tab.loadingStatus = 'more'
					tab.pageNum = 0
					tab.list = []
					await this.loadMore()
				} else {
					this.$refs.udb2.loadData({
						clear: true
					})
				}
			},
			async loadMore() {
				let tab = this.tabs[this.tabIdx]
				if (tab.loadingStatus == 'noMore' || tab.loadingStatus == 'loading') {
					return
				}
				let prevStatus = tab.loadingStatus
				tab.loadingStatus = 'loading'
				try {
					let params = {
						pageNum: tab.pageNum + 1,
						pageSize: tab.pageSize
					}
					if (this.selectedStoreIdx != 0) {
						params.storeId = this.storeOption[this.selectedStoreIdx]._id
					}
					let res = await storeSigner.getMySignRecords(params)
					if (tab.pageNum == 0) {
						tab.total = res.total
					}
					if (res.list.length) {
						tab.pageNum += 1
						tab.list = tab.list.concat(res.list)
					}
					tab.loadingStatus = tab.total == tab.list.length ? 'noMore' : 'more'
					console.log("tab", tab)
				} catch (e) {
					console.error(e)
					tab.loadingStatus = prevStatus
				}
			},
			handleTabChange(idx) {
				this.tabIdx = idx
			},
			isExpired(item) {
				if (!item.checkRecords) {
					if (item.deadline && item.deadline < Date.now()) {
						return true
					}
				} else {
					let r = item.checkRecords[item.checkRecords.length - 1]
					if (r.checkStatus != 2 && (item.deadline && item.deadline < Date.now())) {
						return true
					}
					return false
				}
			},
			getTaskIcon(item) {
				if (this.isExpired(item)) {
					return 'https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_task_gray.png'
				}
				return 'https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_task.png'
			},
			parseStatus(item) {
				if (!item.checkRecords) {
					if (item.deadline && item.deadline < Date.now()) {
						return '已超时'
					}
					return '待完成'
				} else {
					let r = item.checkRecords[item.checkRecords.length - 1]
					if (r.checkStatus != 2 && item.deadline && item.deadline < Date.now()) {
						return '已超时'
					}
					return statusDic[r.checkStatus + ''] || '-'
				}
			},
			statusClass(item) {
				if (!item.checkRecords) {
					if (item.deadline && item.deadline < Date.now()) {
						return 'status-expired'
					}
					return 'status-init'
				} else {
					let r = item.checkRecords[item.checkRecords.length - 1]
					if (r.checkStatus != 2 && item.deadline && item.deadline < Date.now()) {
						return 'status-expired'
					}
					if (r.checkStatus == 1 || r.checkStatus == 3) {
						return 'status-pending'
					} else if (r.checkStatus == 2) {
						return 'status-pass'
					} else if (r.checkStatus == 0) {
						return 'status-init'
					} else if (r.checkStatus == -1) {
						return 'status-reject'
					}
				}
			},
			handleTaskItemClick(item) {
				if (this.isExpired(item)) {
					return
				}
				uni.navigateTo({
					url: './task-detail?taskId=' + item._id,
					events: {
						changed: () => {
							this.needReload = true
						}
					}
				})
			},
			//评价
			evaluate(item) {
				console.log("评价", item)
				this.evaluationObj.signId = item._id;

				this.evaluationIsShow = true
			},
			evaluateClear() {
				this.evaluationObj = {
					environment: 0,
					serve: 0,
					script: 0,
					clientdm: 0,
					clientfeedback: '',
					signId: ''
				}
				this.evaluationIsShow = false;

			},
			onDetail(id) {
				this.taskDetail = id

				this.onDetailIsShow = true




				console.log("id", id)
			},
			async onEvaluate() {
				console.log("提交参数", this.evaluationObj)
				const res = await storeSigner.scriptEvaluation(this.evaluationObj);
				if (res == 0) {
					this.evaluationIsShow = false
					this.evaluationObj = {
						environment: 0,
						serve: 0,
						script: 0,
						clientdm: 0,
						clientfeedback: '',
						signId: ''
					}
					this.reload()
				}
			}
		}
	}
</script>

<style>
	page {
		color: #000;
	}
</style>
<style lang="scss" scope>
	/deep/ .u-sticky-wrap {
		background-color: #ffffff00 !important;
	}

	.top-bar {
		height: 88rpx;
		background-color: #fff;
		border-radius: 22rpx;
		padding: 0 20rpx;
		font-weight: 600;
	}

	.u-image {
		line-height: 1;
	}

	.link {
		border-radius: 12rpx;
		border: 2rpx solid rgba(255, 255, 255, 0.5);
		padding: 4rpx 20rpx;
		font-size: 24rpx;
	}

	.status-tag {
		height: 44rpx;
		line-height: 44rpx;
		border-radius: 22rpx;
		color: #fff;
		font-size: 24rpx;
		padding: 0 20rpx;
	}

	.status-pass {
		background: #FF7D66;
	}

	.status-pass-2 {
		background: rgb(254, 255, 154);
	}

	.status-reject {
		background: #FF7D66;
	}

	.status-pending {
		background: rgba(255, 159, 67, 0.22);
		border: 2rpx solid #FF9F43;
		color: #FF9F43;
	}

	.status-expired {
		background: rgba(216, 216, 216, 0.37);
		color: #A4A4A4;
	}

	.status-init {
		background: rgba(255, 125, 102, 0.30);
		border: 2rpx solid #FF7D66;
		color: #E54428;
	}

	.text-rewards {
		font-size: 30rpx;
		font-weight: 600;
		color: #FF8900;
	}

	.u-tabs {
		background: #EBEBEB !important;
		height: 100rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 0 30rpx;
		border-radius: 50rpx;
	}

	.uni-list {
		border-radius: 20rpx;
	}

	.integral-card {
		background-image: url(https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/bg-integral.png);
		background-size: 100% 100%;
		height: 272rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 30rpx;
		color: #fff;

		.text-integral-label {
			font-size: 28rpx;
		}

		.text-integral {
			font-size: 72rpx;
		}
	}

	.item-bottom {
		background: #FFFBF6;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-top: 20rpx;
	}

	.item-bottom * {
		font-size: 24rpx;
	}

	.task-item {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 30rpx;
		border-radius: 20rpx;
	}

	.task-item.expired {
		background-color: #EBEBEB;
	}
</style>